<template>
  <div>
    <el-form ref="attrForm" :model="attr" :rules="rules">
      <el-form-item label="属性名" label-width="70px" prop="attrName">
        <el-input v-model="attr.attrName" placeholder="请输入属性名" style="width: 400px" />
      </el-form-item>
      <el-form-item label="">
        <el-button type="primary" icon="el-icon-plus" :disabled="!attr.attrName" @click="addAttrValue">添加属性值</el-button>
      </el-form-item>

      <el-table border :data="attr.attrValueList" style="margin-bottom: 20px">
        <el-table-column label="序号" width="80px" type="index" align="center" />
        <el-table-column label="属性值名称">
          <template v-slot="{ row, $index }">
            <el-input :ref="$index" v-model="row.valueName" placeholder="请输入详细属性值" size="mini" @blur="isDelCurrentValue(row, $index)" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{ row, $index }">
            <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" icon="el-icon-info" icon-color="red" title="这是一段内容确定删除吗？" @onConfirm="deleAttrValue(row, $index)">
              <el-tooltip slot="reference" content="删除属性值" placement="top">
                <el-button type="danger" icon="el-icon-delete">删除</el-button>
              </el-tooltip>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <el-button type="primary" @click="submitForm">确定</el-button>
    <el-button @click="$emit('setIsShowList', true)">取消</el-button>
  </div>
</template>

<script>
import { reqSaveOrUpdateAttrInfo } from '@/api/product/attr'
import { mapState } from 'vuex'
export default {
  name: 'SaveList',
  props: {
    attrValue: {
      type: Object,
      default: () => {
        return {
          attrName: '',
          attrValueList: []
        }
      }
    }
  },
  data() {
    //添加属性前的整体校验
    const validatorAttrValueList = (rule, value, callback) => {
      // rule 是原来校验的规则 ，比如说required...
      // value 是待校验的值
      // callback 是一个回调函数，可以添加错误的时候，如果里面有参数，说明需要进行错误提示，如果里面没有参数，则说明校验通过
      // console.log(rule, value)
      if (!value.length) {
        callback(new Error('数组中不能为空，应该至少添加一个属性值'))
        return // 阻止代码向下执行
      }
      callback() // 里面什么参数都没有 则显示校验通过 但是一定要调用一下
    }
    return {
      // attr: {
      //   attrName: '',
      //   attrValueList: [],
      //   categoryId: '',
      //   categoryLevel: 3
      // },
      attr: this.attrValue, //如果有值传递过来，就给attr赋值。如果没有值传递过来,就用默认的
      rules: {
        attrName: [{ required: true, message: '属性名不能为空', trigger: 'blur' }],
        attrValueList: [{ required: true, validator: validatorAttrValueList }]
      }
    }
  },
  methods: {
    // 1. 添加属性和详情属性值  此属性当中，可能会有很多个详细属性值
    addAttrValue() {
      this.attr.attrValueList.push({
        valueName: ''
      })
      // VUE框架对于页面中元素的渲染是异步的
      this.$nextTick(() => {
        this.$refs[this.attr.attrValueList.length - 1].focus()
      })
    },
    isDelCurrentValue(row, $index) {
      if (!row.valueName) {
        //第一种删除方式
        // this.attr.attrValueList.splice($index, 1)
        //第二种删除方式
        this.attr.attrValueList.pop()
      }
    },
    //表单校验
    submitForm() {
      // this.$refs[attrForm].validate((valid) => {
      this.$refs.attrForm.validate(async (valid) => {
        if (valid) {
          if (!this.attr.attrValueList.length) {
            this.$message.error('请至少添加一条属性')
            return
          }
          const { attrName, attrValueList, id } = this.attr
          const { category3Id } = this
          const result = await reqSaveOrUpdateAttrInfo({
            attrName,
            attrValueList,
            categoryId: category3Id,
            categoryLevel: 3,
            id
          })
          if (result.code === 200) {
            this.$message.success(`${id ? '修改' : '添加'}属性成功`)
            this.$emit('setIsShowList', true)
          }
        } else {
          console.log('添加失败')
          return false
        }
      })
    },
    deleAttrValue(row, index) {
      this.attr.attrValueList.splice(index, 1)
    }
  },
  computed: {
    ...mapState('category', ['category3Id'])
  }
}
</script>

<style lang="scss" scoped>
</style>